package id.net.iconpln.bb.client.view;

import id.net.iconpln.bb.client.model.Stock;
import id.net.iconpln.bb.client.service.ApprovalService;
import id.net.iconpln.bb.client.service.ApprovalServiceAsync;
import id.net.iconpln.bb.client.service.PembayaranService;
import id.net.iconpln.bb.client.service.PembayaranServiceAsync;
import id.net.iconpln.bb.client.util.ClientModule;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.extjs.gxt.ui.client.Registry;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Orientation;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.Style.SelectionMode;
import com.extjs.gxt.ui.client.binding.FormBinding;
import com.extjs.gxt.ui.client.core.FastMap;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.event.BaseEvent;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.Events;
import com.extjs.gxt.ui.client.event.Listener;
import com.extjs.gxt.ui.client.event.MessageBoxEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.ListStore;
import com.extjs.gxt.ui.client.store.Store;
import com.extjs.gxt.ui.client.util.IconHelper;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.LayoutContainer;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.CheckBoxGroup;
import com.extjs.gxt.ui.client.widget.form.ComboBox;
import com.extjs.gxt.ui.client.widget.form.DateField;
import com.extjs.gxt.ui.client.widget.form.DateTimePropertyEditor;
import com.extjs.gxt.ui.client.widget.form.FieldSet;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.SimpleComboBox;
import com.extjs.gxt.ui.client.widget.form.StoreFilterField;
import com.extjs.gxt.ui.client.widget.form.TextField;
import com.extjs.gxt.ui.client.widget.form.ComboBox.TriggerAction;
import com.extjs.gxt.ui.client.widget.grid.ColumnConfig;
import com.extjs.gxt.ui.client.widget.grid.ColumnModel;
import com.extjs.gxt.ui.client.widget.grid.Grid;
import com.extjs.gxt.ui.client.widget.grid.GridSelectionModel;
import com.extjs.gxt.ui.client.widget.layout.FitData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.extjs.gxt.ui.client.widget.layout.FormLayout;
import com.extjs.gxt.ui.client.widget.layout.RowData;
import com.extjs.gxt.ui.client.widget.layout.RowLayout;
import com.extjs.gxt.ui.client.widget.toolbar.LabelToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.SeparatorToolItem;
import com.extjs.gxt.ui.client.widget.toolbar.ToolBar;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.rpc.AsyncCallback;

public class PageRekapBbInvoice extends LayoutContainer {
	
	private final PembayaranServiceAsync service = GWT.create(PembayaranService.class);
	private FormBinding formBindings;  
	private FormData formData;
	private FormPanel panel;
	private ListStore store,storeBaTerima;
	private ComboBox cboBaTerima;
	private Grid grid;
	private TextField pmsk, nop,id_pengiriman,id_pemasok;
	Map mapParam;
	String noinvoice;
	
	  @Override  
	  protected void onRender(Element parent, int index) {  
	    super.onRender(parent, index);  
	    setLayout(new FitLayout());
	    store = new ListStore();
	    storeBaTerima = new ListStore();
	    formData = new FormData("-20"); 
	    ContentPanel cp = new ContentPanel();  
	  
	    cp.setHeaderVisible(false);  
	    cp.setFrame(true);  
	    cp.setSize(900, 400);  
	    cp.setLayout(new RowLayout(Orientation.HORIZONTAL));  
	  
	    grid = createGridPltu();  
	    grid.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);  
	    grid.getSelectionModel().addListener(Events.SelectionChange,  
	        new Listener<SelectionChangedEvent<Stock>>() {  
	          public void handleEvent(SelectionChangedEvent<Stock> be) {  
	            if (be.getSelection().size() > 0) {  
	              formBindings.bind((ModelData) be.getSelection().get(0));  
	            } else {  
	              formBindings.unbind();  
	            }  
	          }  
	        });  	     
	  
	    final FormPanel panel = createForm();  
	    formBindings = new FormBinding(panel, true);  
	    formBindings.setStore((Store) grid.getStore()); 
	    
	    final ToolBar toolBar = new ToolBar();
	    toolBar.add(new LabelToolItem("<b>Daftar Invoice"));
	    toolBar.add(new SeparatorToolItem());
	    toolBar.add(new LabelToolItem("| Filter by No Invoice / Tanggal:"));

		final SimpleComboBox<String> cmbFilter = new SimpleComboBox<String>();
		cmbFilter.setTriggerAction(TriggerAction.ALL);
		cmbFilter.setWidth(100);
		cmbFilter.setVisible(false);
		toolBar.add(cmbFilter);

		StoreFilterField filter = new StoreFilterField() {
			
			@Override
			protected boolean doSelect(Store store, ModelData parent,
					ModelData record, String property, String filter) {
				// TODO Auto-generated method stub
				if(record.get("no_invoice").toString().toUpperCase().indexOf(filter.toUpperCase())>-1){
					return true;
				}
				return false;
			}
		};
		filter.bind(store);
		toolBar.add(filter);
	    
//		Button btcetak = new Button("Cetak", new SelectionListener<ButtonEvent>() {  
//		      @Override  
//		      public void componentSelected(ButtonEvent ce) {
//		    	  
//		      }  
//		    });  
//	    btcetak.setIcon(IconHelper.createStyle("icon-printer"));
	    
	    Button btupdate = new Button("Update", new SelectionListener<ButtonEvent>() {  
		      @Override  
		      public void componentSelected(ButtonEvent ce) {
		    	  MessageBox.confirm("Confirm", "anda yakin Membayar No Invoice:" + noinvoice + "?", new Listener<MessageBoxEvent>() {
						public void handleEvent(MessageBoxEvent be) {
						if(be.getButtonClicked().getText().equals("Yes")){
							 mapParam = new FastMap();
					    	 mapParam.put("no_invoice", noinvoice);
					    	 mapParam.put("updateby", Registry.get("whoAmI"));
					    	 mapParam.put("app_access", "WEB");
					    	 mapParam.put("crud", "UPDATE");
							service.insertpembayaran("INVOICE", mapParam,new AsyncCallback<List<Map>>() {
				    			public void onFailure(Throwable caught) {
				    				GWT.log(caught.getMessage(), null);
				    			}

				    			public void onSuccess(List<Map> result) {
				    				grid.mask("load Data ....","x-mask-loading");
				    				store.removeAll();
				    				getdata();
				    				grid.unmask();
				    				panel.clear();
				    			}
				    		});
					        grid.getStore().commitChanges();
					        Info.display("Notifikasi: ", "Data Berhasil Di Simpan");
								
							
							}
						}
				    });
		      }  
		    });  
	    btupdate.setIcon(IconHelper.createStyle("icon-reza-edit"));
	    
	    toolBar.add(new SeparatorToolItem());
//	    toolBar.add(btcetak);
	    toolBar.add(new SeparatorToolItem());
	    toolBar.add(btupdate);
	    
	    ContentPanel panelgrid = new ContentPanel();
	    panelgrid.setLayoutOnChange(true); 
	    panelgrid.setLayout(new FitLayout());
	    panelgrid.setBorders(false);
	    panelgrid.setHeaderVisible(false);
	    panelgrid.add(grid);
	    panelgrid.setTopComponent(toolBar);
	  
		
		
	    cp.add(panel, new RowData(.4, 1));
	    cp.add(panelgrid, new RowData(.6, 1));
	    
	      mapParam.put("id_pltu", Registry.get("idPltu"));
		  service.getlistpembayaran("LISTBA",mapParam, new AsyncCallback<List<Map>>() {
	  			public void onFailure(Throwable caught) {
	  				GWT.log(caught.getMessage(), null);
	  			}

	  			public void onSuccess(List<Map> result) {	
	  				storeBaTerima.removeAll();
	  				storeBaTerima.add(ClientModule.setListBaseModelFromListMap(result));
	  			}
	  		});
	    
	    
//		setScrollMode(Scroll.AUTO);		
	    add(cp, new FitData(5));  
	  }  
	  
	  private FormPanel createForm() {  
	    panel = new FormPanel();	    
	    panel.setHeaderVisible(false);
	    
	    FieldSet fieldSet = new FieldSet();  
	    fieldSet.setHeading("Kelengkapan Dokumen");  
	    fieldSet.setCollapsible(false);
	    
	    FormLayout layout = new FormLayout();  
	    layout.setLabelWidth(200);  
	    fieldSet.setLayout(layout);
	    
	    FieldSet fieldSet1 = new FieldSet();  
	    fieldSet1.setHeading("Due Date Pembayaran");  
	    fieldSet1.setCollapsible(false);
	    
	    FormLayout layout1 = new FormLayout();  
	    layout1.setLabelWidth(200);  
	    fieldSet1.setLayout(layout1);  
	    
	    final CheckBox checkBast = new CheckBox();  
	  
	    CheckBoxGroup bast = new CheckBoxGroup();  
	    bast.setFieldLabel("Berita Acara Serah Terima");  
	    bast.add(checkBast);  
	    fieldSet.add(bast, formData);

	    final CheckBox checkSkab = new CheckBox();  
		  
	    CheckBoxGroup skab = new CheckBoxGroup();  
	    skab.setFieldLabel("Surat Keterangan Asal Barang");  
	    skab.add(checkSkab);  
	    fieldSet.add(skab, formData);
	    
	    final CheckBox checkKualitasBb = new CheckBox();  
		  
	    CheckBoxGroup kualitasBb = new CheckBoxGroup();  
	    kualitasBb.setFieldLabel("Sertifikat Asli Kualitas Batubara");  
	    kualitasBb.add(checkKualitasBb);  
	    fieldSet.add(kualitasBb, formData);
	    
	    final CheckBox checkKuantitasBb = new CheckBox();  
		  
	    CheckBoxGroup kuantitasBb = new CheckBoxGroup();  
	    kuantitasBb.setFieldLabel("Sertifikat Asli Kuantitas Batubara");  
	    kuantitasBb.add(checkKuantitasBb);  
	    fieldSet.add(kuantitasBb, formData);
	    
	    final CheckBox checkBak = new CheckBox();  
		  
	    CheckBoxGroup bak = new CheckBoxGroup();  
	    bak.setFieldLabel("Berita Acara Keterlambatan");  
	    bak.add(checkBak);  
	    fieldSet.add(bak, formData);
	    
	    final CheckBox checkpjbb = new CheckBox();  
		  
	    CheckBoxGroup pjbb = new CheckBoxGroup();  
	    pjbb.setFieldLabel("Copy PJBB");  
	    pjbb.add(checkpjbb);  
	    fieldSet.add(pjbb, formData);
	    
	    final CheckBox checkpkp = new CheckBox();  
		  
	    CheckBoxGroup pkp = new CheckBoxGroup();  
	    pkp.setFieldLabel("Copy PKP");  
	    pkp.add(checkpkp);  
	    fieldSet.add(pkp, formData);
	    
	    final CheckBox checkBprt = new CheckBox();  
		  
	    CheckBoxGroup bprt = new CheckBoxGroup();  
	    bprt.setFieldLabel("Copy Bukti Pembayaran Royalti Tambang");  
	    bprt.add(checkBprt);  
	    fieldSet.add(bprt, formData);
	    
	    final CheckBox checkpajak = new CheckBox();  
		  
	    CheckBoxGroup pajak = new CheckBoxGroup();  
	    pajak.setFieldLabel("Perpajakan");  
	    pajak.add(checkpajak);  
	    fieldSet.add(pajak, formData);
	    
	    final CheckBox checkNpwp = new CheckBox();  
		  
	    CheckBoxGroup npwp = new CheckBoxGroup();  
	    npwp.setFieldLabel("NPWP");  
	    npwp.add(checkNpwp);  
	    fieldSet.add(npwp, formData);
	    
	    final CheckBox checkAfp = new CheckBox();  
		  
	    CheckBoxGroup afp = new CheckBoxGroup();  
	    afp.setFieldLabel("Asli Faktur Pajak");  
	    afp.add(checkAfp);  
	    fieldSet.add(afp, formData);
	    
	    final CheckBox checkRph = new CheckBox();  
		  
	    CheckBoxGroup rph = new CheckBoxGroup();  
	    rph.setFieldLabel("Rincian Perhitungan Harga");  
	    rph.add(checkRph);  
	    fieldSet.add(rph, formData);
	    
	    final CheckBox checkKwitansi = new CheckBox();  
		  
	    CheckBoxGroup kwitansi = new CheckBoxGroup();  
	    kwitansi.setFieldLabel("Kwitansi");  
	    kwitansi.add(checkKwitansi);  
	    fieldSet.add(kwitansi, formData);
	    
	    final DateField tgl = new DateField();
	    tgl.setPropertyEditor(new DateTimePropertyEditor("dd/MM/yyyy"));
	    tgl.setFieldLabel("Tanggal");
	    fieldSet1.add(tgl, formData);
	    
	    final TextField<String> total = new TextField<String>();
	    total.setFieldLabel("Total Invoice");  
	    fieldSet1.add(total, formData);
	    
	    cboBaTerima = new ComboBox();  
//	    cboJetty.setName("id_unit_jetty");  
	    cboBaTerima.setFieldLabel("BAST");
	    cboBaTerima.setEmptyText("Select BA...");  
	    cboBaTerima.setDisplayField("no_ba_penerimaan");  
	    cboBaTerima.setWidth(150);  
	    cboBaTerima.setStore(storeBaTerima);  
	    cboBaTerima.setTypeAhead(true);  
	    cboBaTerima.setTriggerAction(TriggerAction.ALL);
	    cboBaTerima.addSelectionChangedListener(new SelectionChangedListener<ModelData>() {
	    	@Override
	    	public void selectionChanged(SelectionChangedEvent<ModelData> se) {
	    		// TODO Auto-generated method stub
	    		    nop.setValue(se.getSelectedItem().get("no_pengiriman").toString());
	    			pmsk.setValue(se.getSelectedItem().get("pemasok").toString());
	    			id_pengiriman.setValue(se.getSelectedItem().get("id_pengiriman").toString());
	    			id_pemasok.setValue(se.getSelectedItem().get("id_pemasok").toString());
	    	}
		});
	    fieldSet1.add(cboBaTerima, formData);

	    pmsk = new TextField<String>();
	    pmsk.setFieldLabel("Pemasok");  
	    fieldSet1.add(pmsk, formData);
	    
	    nop = new TextField<String>();
	    nop.setFieldLabel("No Pengiriman");  
	    fieldSet1.add(nop, formData);

	    id_pemasok = new TextField<String>();
	    id_pemasok.setFieldLabel("Pemasok");
	    id_pemasok.setVisible(false);
	    fieldSet1.add(id_pemasok, formData);
	    
	    id_pengiriman = new TextField<String>();
	    id_pengiriman.setFieldLabel("No Pengiriman");
	    id_pengiriman.setVisible(false);
	    fieldSet1.add(id_pengiriman, formData);
	    
	    
	    panel.add(fieldSet1);
	    panel.add(fieldSet);  
	    

	    
	    ContentPanel p = new ContentPanel();
	    p.setHeaderVisible(false);	    
	    p.setButtonAlign(HorizontalAlignment.RIGHT);  
	    
	    p.addButton(new Button("Submit", new SelectionListener<ButtonEvent>() {  
		      @Override  
		      public void componentSelected(ButtonEvent ce) {  
		    	  mapParam = new FastMap();
		    	  	if (checkBast.getValue().equals(true)) {
//		    	  		MessageBox.alert("msg", "value " + checkBast.getValue(), null);
		    	  		mapParam.put("bast", "OK");
		    	  	}else{
		    	  		mapParam.put("bast", "");
		    	  	}
		    	  	if (checkSkab.getValue().equals(true)) {
		    	  		mapParam.put("skab", "OK");
		    	  	}else{
		    	  		mapParam.put("skab", "");
		    	  	}
		    	  	if (checkKualitasBb.getValue().equals(true)) {
		    	  		mapParam.put("kualitasbb", "OK");
		    	  	}else{
		    	  		mapParam.put("kualitasbb", "");
		    	  	}
		    	  	if (checkKuantitasBb.getValue().equals(true)) {
		    	  		mapParam.put("kuantitasbb", "OK");
		    	  	}else{
		    	  		mapParam.put("kuantitasbb", "");
		    	  	}
		    	  	if (checkBak.getValue().equals(true)) {
		    	  		mapParam.put("bak", "OK");
		    	  	}else{
		    	  		mapParam.put("bak", "");
		    	  	}
		    	  	if (checkpjbb.getValue().equals(true)) {
		    	  		mapParam.put("pjbb", "OK");
		    	  	}else{
		    	  		mapParam.put("pjbb", "");
		    	  	}
		    	  	if (checkpkp.getValue().equals(true)) {
		    	  		mapParam.put("pkp", "OK");
		    	  	}else{
		    	  		mapParam.put("pkp", "");
		    	  	}
		    	  	if (checkBprt.getValue().equals(true)) {
		    	  		mapParam.put("bprt", "OK");
		    	  	}else{
		    	  		mapParam.put("bprt", "");
		    	  	}
		    	  	if (checkpajak.getValue().equals(true)) {
		    	  		mapParam.put("pajak", "OK");
		    	  	}else{
		    	  		mapParam.put("pajak", "");
		    	  	}
		    	  	if (checkNpwp.getValue().equals(true)) {
		    	  		mapParam.put("npwp", "OK");
		    	  	}else{
		    	  		mapParam.put("npwp", "");
		    	  	}
		    	  	if (checkAfp.getValue().equals(true)) {
		    	  		mapParam.put("afp", "OK");
		    	  	}else{
		    	  		mapParam.put("afp", "");
		    	  	}
		    	  	if (checkRph.getValue().equals(true)) {
		    	  		mapParam.put("rph", "OK");
		    	  	}else{
		    	  		mapParam.put("rph", "");
		    	  	}
		    	  	if (checkKwitansi.getValue().equals(true)) {
		    	  		mapParam.put("kwitansi", "OK");
		    	  	}else{
		    	  		mapParam.put("kwitansi", "");
		    	  	}
		    	  	
//		    	  	String date = tgl.getRawValue().toString();
//		    	  	final DateTimeFormat dtFormat = DateTimeFormat.getFormat("dd/MM/yyyy");
//					java.util.Date tgl = dtFormat.parse(date);
		    	  	mapParam.put("tgl", tgl.getRawValue().toString());
		    	  	mapParam.put("id_pltu", Registry.get("idPltu"));
		    	  	mapParam.put("id_pjbb", "2");
		    	  	mapParam.put("id_pengiriman", id_pengiriman.getRawValue());
		    	  	mapParam.put("id_pemasok", id_pemasok.getRawValue());
		    	  	mapParam.put("total", total.getRawValue());
		    	  	mapParam.put("createby", Registry.get("whoAmI"));
		    	  	mapParam.put("app_access", "WEB");
		    	  	mapParam.put("crud", "CREATE");
		    	  	 
		    	  	service.insertpembayaran("INVOICE", mapParam,new AsyncCallback<List<Map>>() {
		    			public void onFailure(Throwable caught) {
		    				GWT.log(caught.getMessage(), null);
		    			}

		    			public void onSuccess(List<Map> result) {
		    				grid.mask("load Data ....","x-mask-loading");
		    				store.removeAll();
		    				getdata();
		    				grid.unmask();
		    				panel.clear();
		    			}
		    		});
			        grid.getStore().commitChanges();
			        Info.display("Notifikasi: ", "Data Berhasil Di Simpan");
		    	  
		      }  
		    }));  

	    panel.add(p);
	    
	    p.addButton(new Button("Reset", new SelectionListener<ButtonEvent>() {  
	      @Override  
	      public void componentSelected(ButtonEvent ce) {  
	        grid.getStore().rejectChanges();
	        panel.clear();
	      }  
	    }));  
	    
	    panel.setScrollMode(Scroll.AUTO);
	    
	    return panel;  
	  }  
	  
	  
	  
	  
	  private Grid createGridPltu(){
		    List<ColumnConfig> configs = new ArrayList<ColumnConfig>();  

		    ColumnConfig column = new ColumnConfig(); 
		    
		    store = new ListStore();
		    getdata();
		    
		    
		    column = new ColumnConfig("no_invoice", "No Invoice", 150);  
		    configs.add(column); 
		    
		    column = new ColumnConfig("ba_serahterima", "BA Serah Terima", 150);  
		    configs.add(column); 
		    
		    column = new ColumnConfig("sertifikat_kualitas_bb", "Sertifikat Kualitas", 150);  
		    configs.add(column); 
		    
		    column = new ColumnConfig("sertifikat_kuantitas_bb", "Sertifikat Kuantitas", 150);  
		    configs.add(column); 
		    
		    column = new ColumnConfig("ba_keterlambatan", "BA Keterlambatan", 150);  
		    configs.add(column); 
		    
		    column = new ColumnConfig("copy_pjbb", "Copy PJBB", 150);  
		    configs.add(column); 
		    
		    column = new ColumnConfig("copy_pkp", "Copy PKP", 150);  
		    configs.add(column); 
		    
		    column = new ColumnConfig("copy_pembayaran_royalti", "Copy Bukti Pembayaran Royalti Tambang", 150);  
		    configs.add(column); 
		    
		    column = new ColumnConfig("perpajakan", "Perpajakan", 150);  
		    configs.add(column); 	
		    
		    column = new ColumnConfig("npwp", "NPWP", 150);  
		    configs.add(column); 
		    
		    column = new ColumnConfig("asli_faktur_perpajakan", "Asli Faktur Pajak", 150);  
		    configs.add(column); 
		    
		    column = new ColumnConfig("rincian_perhitungan_harga", "Rincian Perhitungan Harga", 150);  
		    configs.add(column); 
		    
		    column = new ColumnConfig("kwitansi", "Kwitansi", 150);  
		    configs.add(column); 
		    
		    store.setMonitorChanges(true); 
		    ColumnModel cm = new ColumnModel(configs);  
		  
		    grid = new Grid(store, cm);  
		    grid.getView().setEmptyText("Data Empty");  
		    grid.setBorders(true);  
		    
		    final GridSelectionModel csm = new GridSelectionModel();
	        grid.setSelectionModel(csm);
		    grid.addListener(Events.CellClick, new Listener<BaseEvent>() {            
	            public void handleEvent(BaseEvent ge) {
	            	noinvoice = grid.getSelectionModel().getSelectedItem().get("no_invoice");
	            	
	            	
	            	
	              
	            	
	            }
	        });
		    
		  
		    return grid;  
	  }   
	  
	  private void getdata() {
		  mapParam = new FastMap();
		  mapParam.put("id_pltu", Registry.get("idPltu"));
		  service.getlistpembayaran("INVOICE",mapParam, new AsyncCallback<List<Map>>() {
	  			public void onFailure(Throwable caught) {
	  				GWT.log(caught.getMessage(), null);
	  			}

	  			public void onSuccess(List<Map> result) {	
	  				store.removeAll();
	  				store.add(ClientModule.setListBaseModelFromListMap(result));
	  			}
	  		});
	}
	 
}
